<?php
namespace App\Imports;
use App\Exceptions\BobException;
use App\Models\Car;
use App\Models\CarBrand;
use App\Models\Company;
use App\Models\DriverCar;
use App\Models\Drivers;
use App\Models\ServiceType;
use App\Models\User;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
class CarDriverImport implements ToCollection
{
    /**
     * @param Collection $row
     * @throws BobException
     */
    public function collection(Collection  $row)
    {

        $data = $row->toArray();  //接收的对象数据装换为数组
        unset($data[0]);           //去除excel表头
        $car_number = [
            '京','津','冀','晋','蒙','辽','吉','黑','沪','苏','浙','皖','闽','赣','鲁',
            '豫','鄂','湘','粤','桂','琼','渝','川','贵','云','藏','陕','甘','青', '宁','新'
          ]; //判断车牌简称
        DB::beginTransaction();  //开启事务
        try {
            //遍历数组
            foreach ($data as $row) {
               //验证司机姓名长度
                if (mb_strlen($row[0]) > 10) {
                    throw new Exception('司机姓名过长');
                }
                //判断车牌尾号首字母
                $num = mb_substr($row[3], 0, 1, 'utf-8');
                if(!in_array($num, $car_number)){
                    throw new Exception("{$row[3]}车牌首123.$num.不存在");
                }
                //判断车牌简称
                if(!preg_match("/^[A-Z]*$/",$q = mb_substr($row[3], 1, 1, 'utf-8'))){
                    throw new Exception("{$row[3]}车牌简称.$q.错误");
                }
                //判断车牌尾号简称
                if(!preg_match("/^[A-Z0-9]*$/",$car_d = mb_substr($row[3], 2))){
                    throw new Exception("{$row[3]}车牌号.$car_d.不符合规则");
                }
                //判断车牌尾号长度
                $mm = mb_strlen($str =mb_substr($row[3], 2));
                if($mm<5 || $mm>6){
                    throw new Exception("{$row[3]}车牌号长度.$str.不符合规则");
                }
                //验证手机号格式是否正确
                if (!validateChinaPhoneNumber($row[1])) {
                    throw new Exception("{$row[1]}手机格式不对");
                }
                //查询公司是否存在返回id值
                if (!$company_id = Company::where('name', $row[2])->value('id')) {
                    throw new Exception("{$row[2]}公司不存在");
                }
                //查询类型是否存在返回id值
                if (!$type_id = ServiceType::where('name', $row[5])->value('id')) {
                    throw new Exception("{$row[5]}类型不存在");
                }
               //查询品牌是否存在返回id值
                if (!$brand_id = CarBrand::where('name', $row[6])->value('id')) {
                    throw new Exception("{$row[6]}品牌不存在");
                }
                //创建或者查找车俩
                $car = Car::firstOrCreate(
                    ['number' => $row[3]],
                    ['type' => $type_id, 'brand_id' => $brand_id, 'company_id' => $company_id]
                );
                //创建或者查找用户
                $user = User::firstOrCreate(
                    ['phone' => $row[1]]
                );


                //创建或者查找司机
                $driver = Drivers::firstOrCreate(
                    ['phone' => $row[1]],
                    [
                        'real_name' => trim($row[0]),
                        'company_id' => $company_id,
                        'user_id' => $user->id,
                        'status'=>2
                    ]
                );
                //更新司机姓名
                $dr =Drivers::where('phone','=',$row[1])->value('id');
                Drivers::query()->where('id',$dr)->update(['real_name'=>$row[0]]);
                //查找司机是否绑定
                if($number_id = DriverCar::where('car_id',$car->id)
                    ->where('driver_id','=', $driver->id)->value('driver_id')){
                    throw new Exception("{$row[1]}司机已绑定");
                }
                //更新主司机


                if($car_id=DriverCar::where('car_id',$car->id)->where('host','=','1')->value('car_id')){
                    DriverCar::query()->where('car_id',$car_id)->update([
                        'host'=>'0'
                    ]);
                }
                //创建或者查找关联关系
                    DriverCar::firstOrCreate([
                        'car_id' => $car->id,
                        'driver_id' => $driver->id,
                        'host' => trim($row[4]) == '是'? '1': '0'  //转换excel 提交的是:1 其他:0
                    ]);


            }
            DB::commit();  //提交事务
        } catch (Exception $e) {
            DB::rollBack(); //回滚事务
            return_bob($e->getMessage());
        }
    }

}
